package ar.com.sebasoft.rembrandt;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import ar.com.sebasoft.rembrandt.adapter.AlbumAdapter;
import ar.com.sebasoft.rembrandt.model.Album;
import ar.com.sebasoft.rembrandt.util.StringUtil;
import ar.com.sebasoft.rembrandt.util.SystemHelper;

public class GalleryListFragment extends ListFragment implements OnLoadCompleteListener<Cursor> {

	private static final String STATE_ACTIVATED_POSITION = "activated_position";

	private Callbacks mCallbacks = sDummyCallbacks;

	private int mActivatedPosition = ListView.INVALID_POSITION;

	private AlbumAdapter mAdapter = null;

	private boolean hasHappened = false;

	public interface Callbacks {
		/**
		 * Callback para cuando un item fue seleccionado.
		 */
		public void onItemSelected(String id);
	}

	private static Callbacks sDummyCallbacks = new Callbacks() {
		@Override
		public void onItemSelected(String id) {
		}
	};

	public GalleryListFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SystemHelper.setCurrentContext(this.getActivity());
		this.refreshAlbums();
	}

	/**
	 *
	 */
	private void refreshAlbums() {
		// Donde se almacenan las imagenes
		Uri uriExt = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		Uri uriInt = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
		// Las columnas que queremos
		String[] projection = { BaseColumns._ID, MediaColumns.DATA };
		// Solo queremos las miniaturas
		String selection = "";
		CursorLoader cLoaderExt = new CursorLoader(this.getActivity(), uriExt, projection, selection, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
		cLoaderExt.registerListener(0, this);
		CursorLoader cLoaderInt = new CursorLoader(this.getActivity(), uriInt, projection, selection, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
		cLoaderInt.registerListener(0, this);
		Log.d(SystemHelper.APP_TAG, "Start doing load");
		cLoaderExt.startLoading();
		cLoaderInt.startLoading();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		this.setEmptyText(SystemHelper.getLocalizedString(R.string.msg_no_albums));

		this.mAdapter = new AlbumAdapter(this.getActivity(), new ArrayList<Album>());

		// Restore the previously serialized activated item position.
		if ((savedInstanceState != null) && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
			this.setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
		}

		this.checkEasterEgg();
	}

	private void checkEasterEgg() {
		GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
		int anio = cal.get(Calendar.YEAR);
		int anioRembrandt = 1606;
		int mesRembrandt = Calendar.JULY;
		int diaRembrandt = 15;
		if ((cal.get(Calendar.DAY_OF_MONTH) == diaRembrandt) && (cal.get(Calendar.MONTH) == mesRembrandt) && !this.hasHappened) {
			int edad = anio - anioRembrandt;

			// Lets show the Dialog
			Builder builder = new AlertDialog.Builder(this.getActivity());
			builder.setTitle(SystemHelper.getLocalizedString(R.string.msg_bday_rembrandt, edad));
			builder.setMessage(R.string.msg_about_rembrandt);
			builder.setCancelable(false);
			builder.setIcon(R.drawable.ic_launcher);
			builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

				}
			});
			Dialog dialog = builder.create();
			dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
			dialog.show();
			this.hasHappened = true;
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// Activities containing this fragment must implement its callbacks.
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException("Activity must implement fragment's callbacks.");
		}

		this.mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();

		// Reset the active callbacks interface to the dummy implementation.
		this.mCallbacks = sDummyCallbacks;
	}

	@Override
	public void onListItemClick(ListView listView, View view, int position, long id) {
		super.onListItemClick(listView, view, position, id);

		// Notify the active callbacks interface (the activity, if the
		// fragment is attached to one) that an item has been selected.
		this.mCallbacks.onItemSelected(view.getTag().toString());
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (this.mActivatedPosition != AdapterView.INVALID_POSITION) {
			// Serialize and persist the activated item position.
			outState.putInt(STATE_ACTIVATED_POSITION, this.mActivatedPosition);
		}
	}

	/**
	 * Turns on activate-on-click mode. When this mode is on, list items will be
	 * given the 'activated' state when touched.
	 */
	public void setActivateOnItemClick(boolean activateOnItemClick) {
		// When setting CHOICE_MODE_SINGLE, ListView will automatically
		// give items the 'activated' state when touched.
		this.getListView().setChoiceMode(activateOnItemClick ? AbsListView.CHOICE_MODE_SINGLE : AbsListView.CHOICE_MODE_NONE);
	}

	private void setActivatedPosition(int position) {
		if (position == AdapterView.INVALID_POSITION) {
			this.getListView().setItemChecked(this.mActivatedPosition, false);
		} else {
			this.getListView().setItemChecked(position, true);
		}

		this.mActivatedPosition = position;
	}

	@Override
	public void onLoadComplete(Loader<Cursor> cLoader, Cursor cursor) {
		Log.d(SystemHelper.APP_TAG, "Load Complete");

		if ((cursor != null) && (cursor.getCount() > 0)) {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				int col_idx_id = cursor.getColumnIndexOrThrow(BaseColumns._ID);
				int col_idx_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);

				this.agregarAlbumALista(cursor.getLong(col_idx_id), cursor.getString(col_idx_data));
				cursor.moveToNext();
			}
		} else {
			this.setEmptyText(SystemHelper.getLocalizedString(R.string.msg_no_albums));
			Log.d(SystemHelper.APP_TAG, "No pictures for this cursor loader!");
		}
		this.setListAdapter(this.mAdapter);
	}

	private void agregarAlbumALista(long id, String path) {
		Log.d(SystemHelper.APP_TAG, "ID=" + id + " PATH=" + path);

		Album album = new Album(StringUtil.getAlbumName(path), StringUtil.getAlbumPath(path));
		Album encontrado = this.buscarAlbum(album);
		if (encontrado == null) {
			album.sumarFoto();
			if (album.getThumbPath1() == null) {
				album.setThumbPath1(id);
			} else if (album.getThumbPath2() == null) {
				album.setThumbPath2(id);
			} else if (album.getThumbPath3() == null) {
				album.setThumbPath3(id);
			}
			this.mAdapter.add(album);
		} else {
			encontrado.sumarFoto();
			if (encontrado.getThumbPath1() == null) {
				encontrado.setThumbPath1(id);
			} else if (encontrado.getThumbPath2() == null) {
				encontrado.setThumbPath2(id);
			} else if (encontrado.getThumbPath3() == null) {
				encontrado.setThumbPath3(id);
			}
		}
	}

	private Album buscarAlbum(Album album) {
		for (Album itmAlbum : this.mAdapter.getmList()) {
			if (itmAlbum.compareTo(album) == 0) {
				return itmAlbum;
			}
		}
		return null;
	}

}